package ao.util.async;

/**
 * User: aostrovsky
 * Date: 2-Sep-2009
 * Time: 3:47:49 PM
 */
public class BlockingReference<T>
{
    //--------------------------------------------------------------------
    private final Condition IS_SET;
    private       T         val;


    //--------------------------------------------------------------------
    public BlockingReference()
    {
        IS_SET = new Condition(false);
    }


    //--------------------------------------------------------------------
    public void set(T value)
    {
        synchronized (this) {
            assert val == null
                   : "can only be set once";

            val = value;
        }

        IS_SET.setTrue();
    }


    //--------------------------------------------------------------------
    public void waitForSet()
    {
        try {
            IS_SET.waitForTrue();
        } catch (InterruptedException e) {
            throw new Error( e );
        }
    }

    
    //--------------------------------------------------------------------
    public T get() {
        return val;
    }


    //--------------------------------------------------------------------
    public T getWhenSet() {
        waitForSet();
        return val;
    }
}
